<template>
	<view :data-theme="theme">
		<view class='order-submission' :style="platform != 'ios' ? {'margin-top':160+'rpx'}:''">
			<view class="allAddress" :style="store_self_mention ? '':'padding-top:10rpx;'">

			</view>
			<view class="pad30">
				<view class='wrapper borRadius14'>

				</view>
				<view class='wrapper borRadius14'>
					<view class='item'>
						<view>支付方式</view>
						<view class='list'>
							<view class='payItem acea-row row-middle' :class='active==index ?"on":""'
								@tap='payItem(index)' v-for="(item,index) in cartArr" :key='index' v-if="index != 1">
								<view class='name acea-row row-center-wrapper'>
									<view class='iconfont animated'
										:class='(item.icon) + " " + (animated==true&&active==index ?"bounceIn":"")'>
									</view>
									{{item.name}}
								</view>
								<view class='tip'>{{item.title}}</view>
							</view>
						</view>
					</view>
				</view>
				<view class='moneyList borRadius14'>
					<view class='item acea-row row-between-wrapper'>
						<view>商品总价：</view>
						<view class='money'>￥{{orderInfoVo.proTotalFee || 0}}</view>
					</view>
				</view>
				<view class='moneyList borRadius14'>
					<uni-list>
						<!-- 						<uni-list-item :title="coinTitle" clickable @click="showAntCoin()"
							:rightText="creditMoneyTitle" /> -->
						<uni-list-item :title="coinTitle" :rightText="creditMoneyTitle" />
						<uni-list-item title="会员专享立减" rightText="" />
						<uni-list-item :showArrow="couponInfo.length > 0 ? true : false" title="优惠券"
							:rightText="couponCreditTitle" :clickable="couponInfo.length > 0 ? true : false"
							@click="showCoupon()" />
					</uni-list>
				</view>
				<view style='height:120rpx;'></view>
			</view>
			<view class='footer acea-row row-between-wrapper'>
				<view>合计:
					<text class='price_color'>￥{{orderInfoVo.payFee || 0}}</text>
				</view>
				<view class='settlement' style='z-index:100' @tap="SubOrder">立即结算</view>
			</view>
			<view v-show="platform != 'ios'"
				style="display: flex;position: fixed;left: 20rpx;bottom:60rpx;width: calc(100% - 40rpx);height: 40rpx;align-items: center;">
				<label class="radio">
					<radio value="r1" :checked="true" />
				</label>
				<view style="color: #9D9D9D;font-size: 26rpx;margin-top: 4rpx" @click="toDetail()">
					我已经阅读并同意《蚂蚁摄影用户付费协议》
				</view>
			</view>
		</view>
		<form action="" name="punchout_form">
			<view class="alipaysubmit" v-html="formContent"></view>
		</form>
		<antCoin ref="antCoin" :coinNum="coinNumber" @getCoin="handleCoin"></antCoin>
		<coupon ref="coupons" :couponList="couponInfo" @getCoupon="handleCoupon"></coupon>
	</view>
</template>
<script>
	import {
		getUserAntRamain
	} from '@/api/home.js';
	import {
		postOrderComputed,
		wechatOrderPay,
		wechatQueryPayResult,
		loadPreOrderApi
	} from '@/api/order.js';

	import {
		preOrderApi,
		createOrderCourse
	} from '@/api/learnapi.js';

	import {
		mapGetters
	} from "vuex";
	import {
		toLogin
	} from '@/libs/login.js';

	import antCoin from './components/antCoin.vue';
	import coupon from './components/coupon.vue';
	let app = getApp();
	export default {
		components: {
			antCoin,
			coupon,
		},
		data() {
			return {
				platform: uni.getSystemInfoSync().platform,
				checkValue: '',
				orderShow: 'orderShow', //下单页面使用优惠券组件不展示tab切换页
				//支付方式
				cartArr: [{
						"name": "微信支付",
						"icon": "icon-weixin2",
						value: 'weixin',
						title: '微信快捷支付',
						payStatus: 1,
					},
					{
						"name": "余额支付",
						"icon": "icon-yuezhifu",
						value: 'yue',
						title: '可用余额:',
						payStatus: 1,
					},
					{
						"name": "支付宝支付",
						"icon": "icon-zhifubao",
						value: 'alipay',
						title: '支付宝快捷支付',
						payStatus: 1,
					}
				],
				payType: 'weixin', //支付方式
				openType: 1, //优惠券打开方式 1=使用
				active: 0, //支付方式切换
				coupon: {
					coupon: false,
					list: [],
					statusTile: '立即使用'
				}, //优惠券组件
				address: {
					address: false,
					addressId: 0
				}, //地址组件
				addressInfo: {}, //地址信息
				addressId: 0, //地址id
				couponId: 0, //优惠券id
				cartId: '', //购物车id
				userInfo: {}, //用户信息
				mark: '', //备注信息
				couponTitle: '请选择', //优惠券
				coupon_price: 0, //优惠券抵扣金额
				useIntegral: false, //是否使用积分
				integral_price: 0, //积分抵扣金额
				integral: 0,
				ChangePrice: 0, //使用积分抵扣变动后的金额
				formIds: [], //收集formid
				status: 0,
				toPay: false, //修复进入支付时页面隐藏从新刷新页面
				shippingType: 0,
				system_store: {},
				storePostage: 0,
				contacts: '',
				contactsTel: '',
				mydata: {},
				storeList: [],
				store_self_mention: 0,
				cartInfo: [],
				priceGroup: {},
				animated: false,
				totalPrice: 0,
				integralRatio: "0",
				pagesUrl: "",
				payChannel: '',
				news: true,
				again: false,
				addAgain: false,
				orderInfoVo: {},
				orderProNum: 0,
				preOrderNo: '', //预下单订单号
				theme: app.globalData.theme,
				formContent: '',
				buyId: '',
				buyPrice: '',
				buyName: '',
				userId: '',
				//token: '',
				source: '',
				coinNumber: '', //蚂蚁币总数量
				coinTitle: '',
				creditMoneyTitle: '',
				coinPrice: 0,
				couponInfo: [],
				orderType: '',
				couponCreditTitle: '',
				couponCredit: 0,
				appCouponId: 0, //app优惠券id
			};
		},
		computed: {
			...mapGetters(['isLogin', 'systemPlatform', 'productType']),
		},
		onLoad(options) {
			let that = this;
			that.payChannel = that.$wechat.isWeixin() ? 'public' : 'weixinh5';

			that.addressId = options.addressId || 0;


			that.source = options.source;
			that.buyPrice = options.price;
			that.userId = options.userId;
			that.buyName = 'mayihuiyuan';


			that.buyId = options.id || 0;
			that.orderType = options.orderType || 0;

			//that.preOrderApi();
			//that.userId = '337538';
			//获取蚂蚁币和优惠券
			that.getAntCoin();
		},
		methods: {
			getAntCoin() {
				let that = this;
				let params = {};
				params.userId = that.userId;
				params.id = that.buyId;
				params.type = that.orderType;
				getUserAntRamain(params).then(res => {
					if (res.code == 0) {
						if (res.data.mayibi) {
							that.coinNumber = res.data.mayibi.toString();
							if (that.coinNumber > 100) {
								that.coinTitle = '蚂蚁币(共' + that.coinNumber + '个,最高抵扣' + Math.floor(that
										.coinNumber / 100) +
									'元)';
								that.creditMoneyTitle = '-￥' + Math.floor(that.coinNumber / 100);
								that.coinPrice = Math.floor(that.coinNumber / 100);
							} else {
								that.coinTitle = '蚂蚁币(共' + that.coinNumber + '个)';
							}

							that.couponInfo = res.data.coupons; //优惠券
							that.preOrderApi();
						} else {
							that.coinNumber = '0';
							that.coinTitle = '蚂蚁币(共' + that.coinNumber + '个)';
							that.couponInfo = res.data.coupons; //优惠券
							that.preOrderApi();
						}
					}

				})
			},
			handleCoin(data) {
				console.log('蚂蚁币:', data.message);
			},
			handleCoupon(data) {
				let that = this;
				that.couponCreditTitle = '-￥' + data.couponMoney;
				that.couponCredit = data.couponMoney;
				that.appCouponId = data.couponId;
				that.preOrderApi();
				console.log('优惠券金额:  ', data.couponMoney);
				console.log('优惠券id:  ', data.couponId);
			},
			showAntCoin() {
				let that = this;
				that.$refs.antCoin.showPop();
			},
			showCoupon() {
				let that = this;
				that.$refs.coupons.showPop();
			},
			toDetail() {
				//window.open('https://www.mae.vip/MaYiAPP1.2/Section/showContent?cs_id=490', '_blank');
				window.location.href = 'https://www.mae.vip/MaYiAPP1.2/Section/showContent?cs_id=490';
			},
			jqueryUrl(url) {
				let arr = url.split('?');
				let params = arr[1].split('&');
				let obj = {};
				for (let i = 0; i < params.length; i++) {
					let param = params[i].split('=');
					obj[param[0]] = param[1];
				}
				return obj;
			},
			preOrderApi() {
				let that = this;
				let params = {};
				//String productId, String productName ,String price, String userId
				params.productId = that.buyId;
				params.productName = that.buyName;
				params.price = that.buyPrice - that.coinPrice - that.couponCredit;
				params.userId = that.userId;
				preOrderApi(params).then(res => {
					this.preOrderNo = res.data.preOrderNo;
					this.getloadPreOrder();
				})
			},
			// 订单详情
			getloadPreOrder: function() {
				loadPreOrderApi(this.preOrderNo).then(res => {
					let orderInfoVo = res.data.orderInfoVo
					this.orderInfoVo = orderInfoVo;
					this.cartInfo = orderInfoVo.orderDetailList;
					this.orderProNum = orderInfoVo.orderProNum;
					this.address.addressId = this.addressId ? this.addressId : orderInfoVo.addressId;


					this.store_self_mention = res.data.storeSelfMention == 'true' && this.productType ===
						'normal' ? true : false;
				}).catch(err => {
					return this.$util.Tips({
						title: err
					});
				})
			},
			// 计算订单价格
			computedPrice: function() {
				let shippingType = this.shippingType;
				postOrderComputed({
					addressId: this.address.addressId,
					useIntegral: this.useIntegral ? true : false,
					couponId: this.couponId,
					shippingType: parseInt(shippingType) + 1,
					preOrderNo: this.preOrderNo
				}).then(res => {
					let data = res.data;
					this.orderInfoVo.couponFee = data.couponFee;
					//赋值操作，userIntegral 当前积分，surplusIntegral 剩余积分
					this.orderInfoVo.userIntegral = data.surplusIntegral;
					this.orderInfoVo.deductionPrice = data.deductionPrice;
					this.orderInfoVo.freightFee = data.freightFee;
					this.orderInfoVo.payFee = data.payFee;
					this.orderInfoVo.proTotalFee = data.proTotalFee;
					this.orderInfoVo.useIntegral = data.useIntegral;
					this.orderInfoVo.usedIntegral = data.usedIntegral;
					this.orderInfoVo.surplusIntegral = data.surplusIntegral;
					//this.orderInfoVo.userIntegral = data.userIntegral;
				}).catch(err => {
					return this.$util.Tips({
						title: err
					});
				});
			},
			payItem: function(e) {
				let that = this;
				let active = e;
				that.active = active;
				that.animated = true;
				that.payType = that.cartArr[active].value;

				// #ifdef H5
				if (that.payType == 'alipay') {
					that.payChannel = 'alipayH5';
				} else {
					that.payChannel = 'weixinh5';
				}
				console.log(that.payChannel)
				// #endif
				that.computedPrice();
				setTimeout(function() {
					that.car();
				}, 500);
			},
			couponTap: function() {
				this.coupon.coupon = true;
				if (!this.coupon.list.length) this.getCouponList();
			},
			car: function() {
				let that = this;
				that.animated = false;
			},
			realName: function(e) {
				this.contacts = e.detail.value;
			},
			phone: function(e) {
				this.contactsTel = e.detail.value;
			},
			payment: function(data) {
				let that = this;
				createOrderCourse(data).then(res => {
					that.getOrderPay(res.data.orderNo, '支付成功');
				}).catch(err => {
					uni.hideLoading();
					return that.$util.Tips({
						title: err
					});
				});
			},
			getOrderPay: function(orderNo, message) {
				let that = this;
				let goPages = '/pages/app_h5_pay_status/index?order_id=' + orderNo + '&msg=' + message + '&buyType=' +
					'会员';
				wechatOrderPay({
					orderNo: orderNo,
					payChannel: that.payChannel,
					payType: that.payType,
					scene: that.productType === 'normal' ? 0 : 1177, //下单时小程序的场景值
					fq: 0,
				}).then(res => {
					let jsConfig = res.data.jsConfig;
					switch (res.data.payType) {
						case 'weixin':
							that.weixinPay(jsConfig, orderNo, goPages);
							break;
						case 'yue':
							uni.hideLoading();
							return that.$util.Tips({
								title: message
							}, {
								tab: 5,
								url: goPages + '&status=1'
							});
							break;
						case 'weixinh5':
							uni.hideLoading();
							uni.setStorage({
								key: 'orderNo',
								data: orderNo
							});
							that.$util.Tips({
								title: '订单创建成功'
							}, {
								tab: 5,
								url: goPages + '&status=0'
							});
							setTimeout(() => {
								location.href = jsConfig.mwebUrl + '&orderNo=' + orderNo;
							}, 100)
							break;
						case 'alipay':
							//#ifdef H5
							if (this.$wechat.isWeixin()) {
								uni.redirectTo({
									url: `/pages/users/alipay_invoke/index?id=${orderNo}`
								});
							} else {
								//h5支付
								uni.hideLoading();
								//alert('!!!!!!' + JSON.stringify(res.data.alipayRequest))
								that.formContent = res.data.alipayRequest;
								uni.setStorage({
									key: 'orderNo',
									data: orderNo
								});

								let platform = uni.getSystemInfoSync().platform; //手机类型
								console.log(platform);
								if (platform == 'ios') {
									window.webkit.messageHandlers.sendOrderNo.postMessage({
										"orderNo": orderNo
									});
								}

								that.$nextTick(() => {
									document.forms['punchout_form'].submit();
								})
							}
							//#endif
							break;
					}
				}).catch(err => {
					uni.hideLoading();
					return that.$util.Tips({
						title: err
					});
				});
			},
			weixinPay(jsConfig, orderNo, goPages) {
				let that = this;
				// #ifdef H5
				let data = {
					timestamp: jsConfig.timeStamp,
					nonceStr: jsConfig.nonceStr,
					package: jsConfig.packages,
					signType: jsConfig.signType,
					paySign: jsConfig.paySign
				};
				that.$wechat.pay(data).then(res => {
					if (res.errMsg == 'chooseWXPay:cancel') {
						uni.hideLoading();
						return that.$util.Tips({
							title: '取消支付'
						}, {
							tab: 5,
							url: goPages + '&status=2'
						});
					} else {
						wechatQueryPayResult(orderNo).then(res => {
							uni.hideLoading();
							return that.$util.Tips({
								title: '支付成功',
								icon: 'success'
							}, {
								tab: 5,
								url: goPages
							});
						}).cache(err => {
							uni.hideLoading();
							return that.$util.Tips({
								title: err
							});
						})
					}
				}).cache(res => {
					uni.hideLoading();
					return that.$util.Tips({
						title: '取消支付'
					}, {
						tab: 5,
						url: goPages + '&status=0'
					});
				});
				// #endif
			},
			SubOrder(e) {
				let that = this,
					data = {};

				if (!that.payType) return that.$util.Tips({
					title: '请选择支付方式'
				});
				data = {
					realName: that.contacts,
					phone: that.contactsTel,
					addressId: that.address.addressId,
					//couponId: that.couponId,
					payType: that.payType,
					useIntegral: that.useIntegral,
					preOrderNo: that.preOrderNo,
					mark: that.mark,
					storeId: that.system_store.id || 0,
					shippingType: that.$util.$h.Add(that.shippingType, 1),
					payChannel: that.payChannel,
					source: that.source,
					couponPrice: that.couponCredit, //优惠券金额
					couponId: that.appCouponId, //优惠券Id
					integralPrice: that.coinPrice, //蚂蚁币数量 除以100了
				};
				console.log('===' + JSON.stringify(data))
				//return;
				uni.showLoading({
					title: '订单支付中'
				});
				// #ifndef MP
				that.payment(data);
				// #endif
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.uni-list-item__container {
		padding-left: 0;
	}

	/deep/.uni-list-item__content-title[data-v-296a3d7e] {
		font-size: 13px;
		color: #3b4144;
	}

	/deep/.uni-icon-wrapper[data-v-296a3d7e] {
		padding: 0 0px;
	}

	/deep/.uni-list-item__extra-text[data-v-296a3d7e] {
		color: #ea5550;
		font-size: 12px;
	}

	.font_color {
		@include main_color(theme);
	}

	.price_color {
		@include price_color(theme);
	}

	.line2 {
		width: 504rpx;
	}

	.textR {
		text-align: right;
	}

	.order-submission .line {
		width: 100%;
		height: 3rpx;
	}

	.order-submission .line image {
		width: 100%;
		height: 100%;
		display: block;
	}

	.order-submission .address {
		padding: 28rpx;
		background-color: #fff;
		box-sizing: border-box;
	}

	.order-submission .address .addressCon {
		width: 596rpx;
		font-size: 26rpx;
		color: #666;
	}

	.order-submission .address .addressCon .name {
		font-size: 30rpx;
		color: #282828;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.order-submission .address .addressCon .name .phone {
		margin-left: 50rpx;
	}

	.order-submission .address .addressCon .default {
		margin-right: 12rpx;
	}

	.order-submission .address .addressCon .setaddress {
		color: #333;
		font-size: 28rpx;
	}

	.order-submission .address .iconfont {
		font-size: 35rpx;
		color: #707070;
	}

	.order-submission .allAddress {
		width: 100%;
		@include index-gradient(theme);
		// padding: 100rpx 30rpx 0 30rpx;
		padding: 150rpx 30rpx 0 30rpx;
	}

	.order-submission .allAddress .nav {
		width: 690rpx;
		margin: 0 auto;
	}

	.order-submission .allAddress .nav .item {
		width: 334rpx;
	}

	.order-submission .allAddress .nav .item.on {
		position: relative;
		width: 230rpx;
	}

	.order-submission .allAddress .nav .item.on::before {
		position: absolute;
		bottom: 0;
		content: "快递配送";
		font-size: 28rpx;
		display: block;
		height: 0;
		width: 336rpx;
		border-width: 0 20rpx 80rpx 0;
		border-style: none solid solid;
		border-color: transparent transparent #fff;
		z-index: 2;
		border-radius: 14rpx 36rpx 0 0;
		text-align: center;
		line-height: 80rpx;
	}

	.order-submission .allAddress .nav .item:nth-of-type(2).on::before {
		content: "到店自提";
		border-width: 0 0 80rpx 20rpx;
		border-radius: 36rpx 14rpx 0 0;
	}

	.order-submission .allAddress .nav .item.on2 {
		position: relative;
	}

	.order-submission .allAddress .nav .item.on2::before {
		position: absolute;
		bottom: 0;
		content: "到店自提";
		font-size: 28rpx;
		display: block;
		height: 0;
		width: 401rpx;
		border-width: 0 0 60rpx 60rpx;
		border-style: none solid solid;
		border-color: transparent transparent rgba(255, 255, 255, 0.6);
		border-radius: 36rpx 14rpx 0 0;
		text-align: center;
		line-height: 60rpx;
	}

	.order-submission .allAddress .nav .item:nth-of-type(1).on2::before {
		content: "快递配送";
		border-width: 0 60rpx 60rpx 0;
		border-radius: 14rpx 36rpx 0 0;
	}

	.order-submission .allAddress .address {
		width: 690rpx;
		max-height: 180rpx;
		margin: 0 auto;
	}

	.order-submission .allAddress .line {
		width: 100%;
		margin: 0 auto;
	}

	.order-submission .wrapper .item .discount .placeholder {
		color: #ccc;
	}

	.order-submission .wrapper {
		background-color: #fff;
		margin-top: 15rpx;
	}

	.order-submission .wrapper .item {
		padding: 27rpx 24rpx;
		font-size: 30rpx;
		color: #333333;
		border-bottom: 1px solid #F5F5F5;
	}

	.order-submission .wrapper .item .discount {
		font-size: 30rpx;
		color: #333;
	}

	.order-submission .wrapper .item .discount .iconfont {
		color: #515151;
		font-size: 30rpx;
		margin-left: 15rpx;
	}

	.order-submission .wrapper .item .discount .num {
		font-size: 32rpx;
		margin-right: 20rpx;
	}

	.order-submission .wrapper .item .shipping {
		font-size: 30rpx;
		color: #999;
		position: relative;
		padding-right: 58rpx;
	}

	.order-submission .wrapper .item .shipping .iconfont {
		font-size: 35rpx;
		color: #707070;
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		margin-left: 30rpx;
	}

	.order-submission .wrapper .item textarea {
		background-color: #f9f9f9;
		width: auto !important;
		height: 140rpx;
		border-radius: 14rpx;
		margin-top: 30rpx;
		padding: 15rpx;
		box-sizing: border-box;
		font-weight: 400;
	}

	.order-submission .wrapper .item .placeholder {
		color: #ccc;
	}

	.order-submission .wrapper .item .list {
		margin-top: 35rpx;
	}

	.order-submission .wrapper .item .list .payItem {
		border: 1px solid #eee;
		border-radius: 14rpx;
		height: 86rpx;
		width: 100%;
		box-sizing: border-box;
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #282828;
	}

	.order-submission .wrapper .item .list .payItem.on {
		// border-color: #fc5445;
		@include coupons_border_color(theme);
		color: $theme-color;
	}

	.order-submission .wrapper .item .list .payItem .name {
		width: 50%;
		text-align: center;
		border-right: 1px solid #eee;
	}

	.order-submission .wrapper .item .list .payItem .name .iconfont {
		width: 44rpx;
		height: 44rpx;
		border-radius: 50%;
		text-align: center;
		line-height: 44rpx;
		background-color: #fe960f;
		color: #fff;
		font-size: 30rpx;
		margin-right: 15rpx;
	}

	.order-submission .wrapper .item .list .payItem .name .iconfont.icon-weixin2 {
		background-color: #41b035;
	}

	.order-submission .wrapper .item .list .payItem .name .iconfont.icon-zhifubao {
		background-color: #00AAEA;
	}

	.order-submission .wrapper .item .list .payItem .tip {
		width: 49%;
		text-align: center;
		font-size: 26rpx;
		color: #aaa;
	}

	.order-submission .moneyList {
		margin-top: 15rpx;
		background-color: #fff;
		padding: 30rpx;
	}

	.order-submission .moneyList .item {
		font-size: 28rpx;
		color: #282828;
	}

	.order-submission .moneyList .item~.item {
		margin-top: 20rpx;
	}

	.order-submission .moneyList .item .money {
		color: #666666;
	}

	.order-submission .footer {
		width: 100%;
		height: 100rpx;
		background-color: #fff;
		padding: 0 30rpx;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
		position: fixed;
		bottom: 120rpx;
		left: 0;
		height: calc(100rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		height: calc(100rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
	}

	.order-submission .footer .settlement {
		font-size: 30rpx;
		color: #fff;
		width: 240rpx;
		height: 70rpx;
		@include main_bg_color(theme);
		border-radius: 50rpx;
		text-align: center;
		line-height: 70rpx;
	}

	.footer .transparent {
		opacity: 0
	}

	/deep/ checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		@include main_bg_color(theme);
		border: none !important;
		color: #fff !important
	}

	/deep/ checkbox .wx-checkbox-input.wx-checkbox-input-checked {
		@include main_bg_color(theme);
		border: none !important;
		color: #fff !important;
		margin-right: 0 !important;
	}
</style>